<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-Spring-5-访问资源 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="访问资源 Spring为所有的资源访问提供了一个Resource接口。主要提供如下几个方法： getInputStream()：定位并打开资源，" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-Spring-5-访问资源 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-Spring-5-访问资源" />
<meta property="og:description" content="访问资源 Spring为所有的资源访问提供了一个Resource接口。主要提供如下几个方法： getInputStream()：定位并打开资源，" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2019/08/java-framework-spring-5-%E8%AE%BF%E9%97%AE%E8%B5%84%E6%BA%90/" />
<meta property="article:published_time" content="2019-08-15T11:07:30+08:00" />
<meta property="article:modified_time" content="2019-08-15T11:07:30+08:00" />
<meta itemprop="name" content="Java-framework-Spring-5-访问资源">
<meta itemprop="description" content="访问资源 Spring为所有的资源访问提供了一个Resource接口。主要提供如下几个方法： getInputStream()：定位并打开资源，">
<meta itemprop="datePublished" content="2019-08-15T11:07:30&#43;08:00" />
<meta itemprop="dateModified" content="2019-08-15T11:07:30&#43;08:00" />
<meta itemprop="wordCount" content="4108">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-Spring-5-访问资源"/>
<meta name="twitter:description" content="访问资源 Spring为所有的资源访问提供了一个Resource接口。主要提供如下几个方法： getInputStream()：定位并打开资源，"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2019/08/java-framework-spring-5-%E8%AE%BF%E9%97%AE%E8%B5%84%E6%BA%90/"
    >Java-framework-Spring-5-访问资源</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-5-%E8%AE%BF%E9%97%AE%E8%B5%84%E6%BA%90/" class="article-date">
  <time datetime="2019-08-15 11:07:30 &#43;0800 CST" itemprop="datePublished">2019-08-15</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2019/08/java-framework-spring-5-%E8%AE%BF%E9%97%AE%E8%B5%84%E6%BA%90/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 4108words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 9minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="访问资源">访问资源</h1>
<p>Spring为所有的资源访问提供了一个Resource接口。主要提供如下几个方法：</p>
<ul>
<li>getInputStream()：定位并打开资源，返回资源输入流。每次调用都返回新的输入流。调用者必须负责关闭输入流。</li>
<li>exists()：返回Resource资源是否存在。</li>
<li>isOpen()：返回资源是否打开。</li>
<li>getDescription()：返回资源的描述信息，用于资源处理出错时输出该信息，通常是全限定文件名或实际URL。</li>
<li>getFile()：返回资源对应的File对象。</li>
<li>getURL()：返回资源对应的URL对象。</li>
</ul>
<p><del>最后两个方法通常无须使用</del>？？？？？，仅在通过简单方式访问无法实现时，Resource才提供传统的资源访问功能。</p>
<h2 id="resource实现类">Resource实现类</h2>
<p>具体的资源访问由Resource接口的实现类完成。主要提供如下实现类：</p>
<ul>
<li>UrlResource：访问网络的实现类。</li>
<li>ClassPathResource：访问类加载路径里资源的实现类。</li>
<li>FileSystemResource：访问文件系统里资源的实现类。</li>
<li>ServletContextResource：访问相对于ServletContext路径下的资源的实现类。</li>
<li>InputStreamResource：访问输入流资源的实现类。</li>
<li>ByteArrayResource：访问字节数组资源的实现类。</li>
</ul>
<h3 id="urlresource">UrlResource</h3>
<p>URL资源通常应该提供标准的协议前缀。如：file:用于访问文件系统，http:用于通过HTTP协议访问资源，ftp:用于通过FTP协议访问资源等。</p>
<p>示例（将book.xml放在应用的当前路径下）：</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;计算机书籍列表&gt;
	&lt;书&gt;
		&lt;书名&gt;疯狂Java讲义&lt;/书名&gt;
		&lt;作者&gt;李刚&lt;/作者&gt;
	&lt;/书&gt;
	&lt;书&gt;
		&lt;书名&gt;轻量级Java EE企业应用实战&lt;/书名&gt;
		&lt;作者&gt;李刚&lt;/作者&gt;
	&lt;/书&gt;
&lt;/计算机书籍列表&gt;
</code></pre>
<pre><code>public class UrlResourceTest{
	public static void main(String[] args) throws Exception{

		UrlResource ur = new UrlResource(&quot;file:book.xml&quot;);

		System.out.println(ur.getFilename());
		System.out.println(ur.getDescription());

		SAXReader reader = new SAXReader();
		Document doc = reader.read(ur.getFile());

		Element el = doc.getRootElement();
		List l = el.elements();

		for (Iterator it = l.iterator();it.hasNext() ; ){
			// 每个节点都是&lt;书&gt;节点
			Element book = (Element)it.next();
			List ll = book.elements();
			// 遍历&lt;书&gt;节点的全部子节点
			for (Iterator it2 = ll.iterator();it2.hasNext() ; ){
				Element eee = (Element)it2.next();
				System.out.println(eee.getText());
			}
		}
	}
}
</code></pre>
<p>file:路径问题，如何解决呢？？？？？？？
答：参看“ApplicationContext访问资源”一节的第4点，file:前缀的用法。</p>
<h3 id="classpathresource">ClassPathResource</h3>
<p>方便访问类加载路径下的资源，尤其对于web应用，ClassPathResource可自动搜索位于WEB-INF/classes下的资源文件，无须使用绝对路径。</p>
<p>示例：</p>
<pre><code>public class ClassPathResourceTest{
	public static void main(String[] args) throws Exception{

		ClassPathResource cr = new ClassPathResource(&quot;book.xml&quot;);

		System.out.println(cr.getFilename());
		System.out.println(cr.getDescription());
		
		//...

	}
}
</code></pre>
<p>在某个包下的文件也能找到，不用写路径。</p>
<h3 id="filesystemresource">FileSystemResource</h3>
<p>要求：资源位于本地文件系统内，资源字符串是完整路径（绝对路径）或位于项目根目录下（跟pom.xml同一目录）。</p>
<h3 id="servletcontextresource">ServletContextResource</h3>
<p>将book.xml放在WEB-INF路径下，然后在jsp中使用ServletContextResource来访问该文件。</p>
<pre><code>&lt;%@ page contentType=&quot;text/html; charset=GBK&quot; language=&quot;java&quot; errorPage=&quot;&quot; %&gt;
&lt;%@ page import=&quot;org.springframework.web.context.support.ServletContextResource&quot;%&gt;
&lt;%@ page import=&quot;org.dom4j.*,org.dom4j.io.*,java.util.*&quot;%&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
	&lt;title&gt;测试ServletContextResource&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h3&gt;测试ServletContextResource&lt;/h3&gt;
&lt;%
// 从Web Context下的WEB-INF路径下读取book.xml资源
ServletContextResource src = new ServletContextResource(application , &quot;WEB-INF/book.xml&quot;);

//...

%&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3 id="inputstreamresource">InputStreamResource</h3>
<p>InputStreamResource是访问二进制输入流资源，是一个总被打开的Resource，因此，如果需要多次读取某个流，就不要使用InputStreamResource。</p>
<p>不建议使用InputStreamResource，而应尽量使用ByteArrayResource或FileSystemResource代替它。</p>
<p>ByteArrayResource用于直接访问字节数组，是将字节数组包装成了Resource。</p>
<pre><code>public class ByteArrayResourceTest{
	public static void main(String[] args) throws Exception{
		String file = &quot;&lt;?xml version='1.0' encoding='GBK'?&gt;&quot;
			+ &quot;&lt;计算机书籍列表&gt;&lt;书&gt;&lt;书名&gt;疯狂Java讲义&quot;
			+ &quot;&lt;/书名&gt;&lt;作者&gt;李刚&lt;/作者&gt;&lt;/书&gt;&lt;书&gt;&lt;书名&gt;&quot;
			+ &quot;轻量级Java EE企业应用实战&lt;/书名&gt;&lt;作者&gt;李刚&quot;
			+ &quot;&lt;/作者&gt;&lt;/书&gt;&lt;/计算机书籍列表&gt;&quot;;
			
		byte[] fileBytes = file.getBytes();
		ByteArrayResource bar = new ByteArrayResource(fileBytes);

		System.out.println(bar.getDescription());

		SAXReader reader = new SAXReader();
		Document doc = reader.read(bar.getInputStream());
		// 获取根元素
		Element el = doc.getRootElement();
		List l = el.elements();
		// 遍历根元素的全部子元素
		//...

	}
}
</code></pre>
<h2 id="resourceloader和resourceloaderaware接口">ResourceLoader和ResourceLoaderAware接口</h2>
<ul>
<li>ResourceLoader：该接口的实现类的实例可以获得一个Resource实例。</li>
<li>ResourceLoaderAware：该接口的实现类的实例将获得一个ResourceLoader的引用。</li>
</ul>
<p>ResourceLoader接口有如下方法：</p>
<ul>
<li>Resource getResource(String location)：该方法用于返回一个Resource实例。</li>
</ul>
<p>ApplicationContext的实现类都实现了ResourceLoader接口，因此ApplicationContext可用于直接获取Resource实例。</p>
<p>某个ApplicationContext实例获取Resource实例时，默认采用与ApplicationContext相同的资源访问策略。如下代码：</p>
<pre><code>Resource res = ctx.getResource(“some/resource/path/myTemplate.txt”);
</code></pre>
<p>如果ctx是FileSystemXmlApplicationContext，则res就是FileSystemResource；如果ctx是ClassPathXmlApplicationContext，则res就是ClassPathResource等。</p>
<pre><code>public class ResourceLoaderTest{
	public static void main(String[] args) throws Exception{
//		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);
		ApplicationContext ctx = new FileSystemXmlApplicationContext(&quot;beans.xml&quot;);
		Resource res = ctx.getResource(&quot;book.xml&quot;);
		//....
}
</code></pre>
<p>也可以强制指定实现类：</p>
<pre><code>Resource res = ctx.getResource(“classpath:myTemplate.txt”);//ClassPathResource
Resource res = ctx.getResource(“file:myTemplate.txt”);	//UrlResource
Resource res = ctx.getResource(“http:myTemplate.txt”);//UrlResource
</code></pre>
<p>实现ResourceLoaderAware接口，有如下方法：</p>
<ul>
<li>setResourceLoader(ResourceLoader resourceLoader)，resourceLoader就是ResourceLoader的引用，通过resourceLoader.getResource()就可以访问资源了。</li>
</ul>
<h2 id="resource作为属性">Resource作为属性</h2>
<p>上面的使用Resource实现类或ApplicationContext来获取资源资源位置（路径）写在代码里了。这里使用Resource作为属性，Spring负责注入，实现解耦。</p>
<p>（这种方式是通过xml配置好资源位置（路径），并创建好实例，再注入到属性中）</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd&quot;&gt;
	
	&lt;bean id=&quot;test&quot; class=&quot;org.crazyit.app.service.TestBean&quot;
		p:res=&quot;classpath:book.xml&quot;/&gt;
&lt;/beans&gt;
</code></pre>
<pre><code>public class TestBean{
	private Resource res;

	public void setRes(Resource res){
		this.res = res;
	}
	
	public void parse()throws Exception{

		System.out.println(res.getFilename());
		System.out.println(res.getDescription());
		// 创建基于SAX的dom4j的解析器
		SAXReader reader = new SAXReader();
		Document doc = reader.read(res.getFile());
		// 获取根元素
		//...
}
</code></pre>
<p>示例中要为resource提供setter方法。</p>
<p>但这各方式只适用于xml配置方式，“零配置”方式如何实现呢？？？？</p>
<h2 id="applicationcontext访问资源">ApplicationContext访问资源</h2>
<p>前面“ResourceLoader和ResourceLoaderAware接口”中已经提到，可以使用ApplicationContext来访问资源。在此需要注意ApplicationContext访问资源的策略：</p>
<p>1、使用ApplicationContext实现类指定访问策略：不同的实现类对应不同的策略。</p>
<ul>
<li>ClassPathXmlApplicationContext：对应使用ClassPathResource进行资源访问。</li>
<li>FileSystemXmlApplicationContext：对应使用FileSystemResource进行资源访问。</li>
<li>XmlWebApplicationContext：对应使用ServletContextResource进行资源访问。</li>
</ul>
<p>2、使用前缀指定访问策略</p>
<p>如下代码，虽然使用了FileSystemXmlApplicationContext，但却是从类路径开始搜索文件：</p>
<p><code>ApplicationContext ctx = new FileSystemXmlApplicationContext(&quot;classpath:beans.xml&quot;);</code></p>
<p>但这种方式仅仅对当次访问有效，程序后面进行资源访问时，还是会根据	ApplicationContext的实现类来选择对应的资源访问策略。</p>
<p>3、classpath*:前缀的用法</p>
<p>1）<code>classpath*</code>:前缀会加载多个xml配置文件。</p>
<p>如<code>ApplicationContext ctx = new FileSystemXmlApplicationContext(&quot;classpath*:beans.xml&quot;);</code>会搜索classpath下所有的beans.xml（就算在不同的包中，只要名称是bean.xml的），不管有多少个，最终都会合并成一个ApplicationContext。</p>
<p>2）<code>“classpath:beans.xml”</code>则只加载第一个符合条件的XML文件。</p>
<p>3）classpath*:前缀仅对ApplicationContext有效。</p>
<p>4）另外还有一个加载多个文件的方法：</p>
<p><code>ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;classpath:beans*.xml&quot;);</code>在类加载路径下搜索beans开关的xml文件。</p>
<p>如果使用FileSystemXmlApplicationContext的话，如下语句也是合法的：<code>ApplicationContext ctx = new FileSystemXmlApplicationContext(&quot;classpath*:beans*.xml&quot;);</code></p>
<p>4、file:前缀的用法</p>
<p>用file:前缀来区分相对路径与绝对路径。如下：</p>
<pre><code>ApplicationContext ctx = new FileSystemXmlApplicationContext(&quot;file:bean.xml&quot;);
ApplicationContext ctx = new FileSystemXmlApplicationContext(&quot;file:/bean.xml&quot;);
</code></pre>
<p>第一条语句是相对路径，以当前工作路径（项目根路径）为路径起点；</p>
<p>第二条语句是绝对路径，以文件系统根路径（如E:/bean.xml）为路径起点。</p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-5-%E8%AE%BF%E9%97%AE%E8%B5%84%E6%BA%90/" title="Java-framework-Spring-5-访问资源" target="_blank" rel="external">https://rulerLwx.gitee.io/2019/08/java-framework-spring-5-%E8%AE%BF%E9%97%AE%E8%B5%84%E6%BA%90/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-4/" title="Java-framework-Spring-4"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-6-aop/"
                    title="Java-framework-Spring-6-AOP"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
